<template>
  <div>
    <a-button type="primary">添加用户</a-button>
    <a-table
      :columns="columns"
      :data-source="roleData"
      bordered
      rowKey="id"
      :pagination="false"
      childrenColumnName="none"
    >
      <template #expandedRowRender="{ record }">
        <a-row
          v-for="item in record.children"
          :key="item.id"
          class="first-line"
        >
          <a-col :span="8"
            ><a-tag
              color="pink"
              closable
              @close.prevent="deleteTag(record.id, item.id)"
              >{{ item.authName }}</a-tag
            ><CaretRightOutlined
          /></a-col>
          <a-col :span="16">
            <a-row
              v-for="(item, index) in item.children"
              :key="item.id"
              :class="index != 0 && 'last-line'"
            >
              <a-col :span="8"
                ><a-tag
                  color="red"
                  closable
                  @close.prevent="deleteTag(record.id, item.id)"
                  >{{ item.authName }}</a-tag
                ><CaretRightOutlined
              /></a-col>
              <a-col :span="16">
                <span v-for="item in item.children" :key="item.id"
                  ><a-tag
                    color="orange"
                    closable
                    @close.prevent="deleteTag(record.id, item.id)"
                    >{{ item.authName }}</a-tag
                  ></span
                >
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </template>
      <template #index="{ index }">
        {{ index }}
      </template>
      <template #btn="{ record }">
        <a-button type="primary" size="small">
          <template #icon><EditOutlined /></template>
          编辑
        </a-button>
        <a-button type="danger" size="small">
          <template #icon><CloseOutlined /></template>
          删除
        </a-button>
        <a-button
          type="primary"
          size="small"
          @click="showModal(record.children, record.id)"
        >
          <template #icon><ToolOutlined /></template>
          分配权限
        </a-button>
      </template>
    </a-table>
    <a-modal
      v-model:visible="visible"
      title="Basic Modal"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-tree
        defaultExpandAll
        :replaceFields="{ children: 'children', title: 'authName', key: 'id' }"
        checkable
        :tree-data="treeData"
        v-model:checkedKeys="checkedKeys"
        @check="check"
      >
      </a-tree>
    </a-modal>
  </div>
</template>
<script>
import { EditOutlined, CloseOutlined, ToolOutlined, CaretRightOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { ref, getCurrentInstance, onMounted, createVNode, toRaw } from 'vue'
import { message, Modal } from 'ant-design-vue';
export default {
  components: {
    EditOutlined,
    CloseOutlined,
    ToolOutlined,
    CaretRightOutlined
  },
  setup () {
    const { proxy } = getCurrentInstance()

    const columns = [
      {
        title: '#',
        // 有唯一的dataIndex不需要设置key
        slots: { customRender: 'index' }
      },
      {
        title: '角色名称',
        dataIndex: 'roleName'
      },
      {
        title: '角色描述',
        dataIndex: 'roleDesc'
      },
      {
        title: '操作',
        slots: { customRender: 'btn' },
        className: 'btn',
        width: '23%'
      },

    ];
    const roleData = ref([])
    const getRole = async () => {
      const { data, meta } = await proxy.$http.get('roles')
      roleData.value = data
    }
    const deleteTag = async (roleId, rightId) => {
      Modal.confirm({
        title: () => '确定删除吗?',
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () =>
          createVNode(
            'div',
            {
              style: 'color:red;',
            },
            '此操作不可逆',
          ),
        async onOk () {
          const { meta } = await proxy.$http.delete(`roles/${roleId}/rights/${rightId}`)
          console.log(meta);
          if (meta.status != 200) return message.error(meta.msg)
          message.success(meta.msg)
          getRole()
        },
        onCancel () {
          message.info('已取消')
        }
      });

    }
    // 分配权限
    const getArr = (data, arr) => {
      data.forEach(item => {
        if (!item.children) {
          return arr.push(item.id)
        }
        getArr(item.children, arr)
      });
    }
    // 数据
    const treeData = ref([])
    // 选中
    const checkedKeys = ref([])
    const visible = ref(false);
    let roleId = 0
    // 分配权限按钮弹出对话框
    const showModal = async (list, id) => {
      roleId = id
      const dataList = toRaw(list)
      getArr(dataList, checkedKeys.value)
      const { meta, data } = await proxy.$http.get('rights/tree')
      if (meta.status !== 200) return message.error(meta.msg)
      treeData.value = data
      visible.value = true
      getRole()
    }
    // 对话框点击确定
    const handleOk = async () => {
      const { meta } = await proxy.$http.post(`roles/${roleId}/rights`, {
        rids: setJurisdiction.join(',')
      })
      if (meta.status !== 200) return message.error(meta.msg)
      message.success(meta.msg)
      checkedKeys.value = []
      visible.value = false
      getRole()
    }
    // 对话框点击取消
    const handleCancel = () => {
      console.log(1);
      checkedKeys.value = []
    }
    // 添加权限需要的数据
    let setJurisdiction = []
    // 点击树的项触发拿到
    const check = (son, father) => {
      console.log(father.halfCheckedKeys);
      setJurisdiction = [...son, ...father.halfCheckedKeys]
      console.log(setJurisdiction);
    }
    onMounted(() => {
      getRole()
    })
    return {
      columns,
      roleData,
      deleteTag,
      visible,
      showModal,
      handleOk,
      treeData,
      checkedKeys,
      handleCancel,
      check
    }
  }
}
</script>
<style lang="less" scoped>
.first-line {
  border-bottom: 1px solid #000;
  display: flex;
  align-items: center;
}
.last-line {
  border-top: 1px solid #000;
}
.ant-tag {
  margin: 10px 0 10px 5px;
}
</style>
<style lang="less">
.btn {
  text-align: center;
}
.btn button {
  margin: 0 5px;
  font-size: 12px;
}
</style>